﻿using System;
using System.Text;
using System.Security.Cryptography;

namespace UniMana.Utils.Helper
{
    public static class ClsMD5
    {
        /// <summary>
        ///  Mã hóa MD5
        /// </summary>
        /// <param name="toEncrypt"></param>
        /// <param name="key"></param>
        /// <param name="useHashing"></param>
        /// <returns></returns>
        public static string Encrypt(this string toEncrypt, string key = "Conket"/*Chìa khoá giải mã*/, bool useHashing = true) //Mã hoá MD5
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);  //Chuyển sang mã UTF-8

            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));  //Mã hoá MD5
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);  //Chuyển sang mã UTF-8

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
       
        /// <summary>
        /// Giải mã MD5
        /// </summary>
        /// <param name="toDecrypt"></param>
        /// <param name="key"></param>
        /// <param name="useHashing"></param>
        /// <returns></returns>
        public static string Decrypt(this string toDecrypt, string key = "Conket", bool useHashing = true) //Giải mã MD5
        {
            if(string.IsNullOrEmpty(toDecrypt.ToString())) return toDecrypt;
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            //Ta cũng có thể chuyên đổi 2 3 tầng mật khẩu

            return UTF8Encoding.UTF8.GetString(resultArray);
        }
        
    }
}
